package com.xiaoshuidi.cloud.module.report.service.finance;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.report.controller.finance.vo.*;
import com.xiaoshuidi.cloud.module.report.convert.finance.DepositOwnerConvert;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportOwnerDepositDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReportOwnerDepositMapper;
import com.xiaoshuidi.cloud.module.report.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.report.framework.security.config.ConfigValues;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
@RequiredArgsConstructor
@Slf4j
public class DepositOwnerServiceImpl implements DepositOwnerService {

    private final ReportOwnerDepositMapper reportOwnerDepositMapper;
    private final OosFileService oosFileService;
    private final ConfigValues configValues;


    @Override
    public DepositOwnerPageRespVO page(DepositOwnerReqVO reqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        reqVO.setTenantId(loginUser.getTenantId());
        long num = reportOwnerDepositMapper.countListForPage(reqVO);
        List<ReportOwnerDepositDO> detailDOList = reportOwnerDepositMapper.selectListForPage(reqVO);
        List<DepositOwnerRespVO> list = DepositOwnerConvert.INSTANCE.convertDOList2VOList(detailDOList);

        DepositOwnerPageRespVO respVO = new DepositOwnerPageRespVO();
        if(CollectionUtils.isEmpty(list)) {
            return respVO;
        }
        List<ReportOwnerDepositDO> totalAmountList = reportOwnerDepositMapper.selectTotalAmount(reqVO);
        respVO.setAmountIn(totalAmountList.stream().filter(e-> "流入".equals(e.getDirection())).map(ReportOwnerDepositDO::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add));
        respVO.setAmountOut(totalAmountList.stream().filter(e-> "流出".equals(e.getDirection())).map(ReportOwnerDepositDO::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add));
        respVO.setAmountReduce(respVO.getAmountIn().subtract(respVO.getAmountOut()));
        respVO.setList(list);
        respVO.setTotal(num);

        return respVO;
    }

    @Override
    public ExportRespVO export(DepositOwnerReqVO req) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        req.setTenantId(loginUser.getTenantId());
        //暂时不分页，当月合同数不会超过2000
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "业主押金报表.xlsx";
        String filePath = configValues.getNfsPath() + File.separator +fileName;
        ExcelWriter excelWriter = EasyExcel.write(filePath, DepositOwnerExportRespVO.class).build();
        WriteSheet sheet = EasyExcel.writerSheet("sheet1").build();
        List<ReportOwnerDepositDO> detailDOList = reportOwnerDepositMapper.selectListForExport(req);
        if(CollectionUtils.isEmpty(detailDOList)){
            throw new ServiceException(ErrorCodeConstants.OWNER_DEPOSIT_NOT_EXISTS);
        }
        List<DepositOwnerExportRespVO> list = DepositOwnerConvert.INSTANCE.convertDOListForExport(detailDOList);
        excelWriter.write(list, sheet);
        excelWriter.finish();
        //上传到oos返回URL
        String url = oosFileService.oosUploadFile(new File(filePath));
        ExportRespVO resp = new ExportRespVO();
        if(url.startsWith("http:")){
            url = url.replace("http:","https:");
        }
        resp.setUrl(url);
        resp.setFileName(fileName);
        return resp;
    }

    @Override
    public List<ReportOwnerDepositDO> selectListUnHandel() {
      return   reportOwnerDepositMapper.selectListUnHandel();
    }

    @Override
    public void updateBatch(List<ReportOwnerDepositDO> list) {
        reportOwnerDepositMapper.updateBatch(list,list.size());
    }


    @Override
    public void updateByOrderIds(List<Long> list) {
        reportOwnerDepositMapper.updateByOrderIds(list);
    }

}
